<?php
/**
 * @Name: UserLogic.php
 * @Author: yashuai
 */

namespace App\Http\Logic\Rbac;

use App\Http\Logic\BaseLogic;
use App\Http\Model\ConstCode;
use App\Http\Model\Rbac\UserModel;
use App\Http\Model\Rbac\UserRoleModel;
use HugCode\PhpUnits\CipherText\Password;

class UserLogic extends BaseLogic
{

    /**
     * @Desc 添加用户
     * @tips 需要事务
     * @return int
     * @throws \App\Exceptions\ApiException
     * @author yashuai
     */
    public function create()
    {
        $info = UserModel::getInfo($this->params['UserName'], 'UserName');
        if (!empty($info)) {
            _throw(106003, '当前用户名已存在');
        }
        $this->params['UserID'] = UserModel::newInsert($this->getParamsTableData());
        if (_array_field($this->params, 'RoleID')) {
            UserRoleLogic::instance($this->params)->setUserRole();
        }
        return $this->params['UserID'];
    }

    /**
     * @Desc 编辑
     * @tips 需要事务
     * @return int
     * @throws \App\Exceptions\ApiException
     * @author yashuai
     */
    public function update()
    {
        $info = UserModel::query()->where([
            ['UserName', '=', $this->params['UserName']],
            ['UserID', '<>', $this->params['UserID']]
        ])->first();
        if (!empty($info)) {
            _throw(106003, '当前用户名已存在');
        }
        $info   = UserModel::userExist($this->params['UserID'], true);
        $data   = $this->getParamsTableData($info);
        $result = UserModel::query()->where(['UserID' => $this->params['UserID']])->update($data);
        if (_array_field($this->params, 'RoleID')) {
            UserRoleLogic::instance($this->params)->setUserRole();
        }
        return $result;
    }

    /**
     * @Desc 删除
     * @return int
     * @throws \App\Exceptions\ApiException
     * @author yashuai
     */
    public function delete()
    {
        UserModel::userExist($this->params['UserID']);
        return UserModel::query()->where(['UserID' => $this->params['UserID']])->update([
            'UserStatus' => ConstCode::BASIC_STATUS_DELETE
        ]);
    }

    /**
     * @Desc 获取用户信息
     * @return array|\Illuminate\Database\Query\Builder|mixed
     * @throws \App\Exceptions\ApiException
     * @author yashuai
     */
    public function info()
    {
        $select        = [
            'UserID', 'UserName', 'NickName', 'UserStatus', 'IsSuper'
        ];
        $info          = UserModel::userExist($this->params['UserID'], true, $select);
        $info['roles'] = UserRoleModel::query()->where('UserID', $this->params['UserID'])->pluck('RoleID');
        $node          = NodeLogic::instance($this->params)->getUserNode(true);
        foreach ($node as $val) {
            $info['authorities'][] = [
                'authority'  => $val['ControllerName'] . ':' . $val['ActionName'],
                'menuId'     => $val['menuId'],
                'parentId'   => $val['parentId'],
                'sortNumber' => $val['NodeOrder'],
                'title'      => $val['title']
            ];
        }
        return $info;
    }

    /**
     * @Desc 数据转为表结构数据
     * @return array
     * @author yashuai
     */
    private function getParamsTableData($info = [])
    {
        $password      = _array_field($this->params, 'UserPassword');
        $password      = empty($password) ? _array_field($info, 'UserPassword', '') : Password::generatePassword($password);
        $defaultSuper  = _array_field($info, 'IsSuper', ConstCode::IS_NO);
        $defaultStatus = _array_field($info, 'UserStatus', ConstCode::BASIC_STATUS_NORMAL);
        $defaultEmail  = _array_field($info, 'UserEmail', '');
        return [
            'UserName'     => $this->params['UserName'],
            'UserPassword' => $password,
            'NickName'     => $this->params['NickName'],
            'UserEmail'    => _array_field($this->params, 'UserEmail', $defaultEmail),
            'IsSuper'      => _array_field($this->params, 'IsSuper', $defaultSuper),
            'UserStatus'   => _array_field($this->params, 'UserStatus', $defaultStatus)
        ];
    }

    /**
     * @Desc 修改密码
     * @return int
     * @throws \App\Exceptions\ApiException
     * @author yashuai
     */
    public function resetPassword()
    {
        UserModel::userExist($this->params['UserID'], true);
        return UserModel::query()->where(['UserID' => $this->params['UserID']])->update([
            'UserPassword' => Password::generatePassword($this->params['UserPassword'])
        ]);
    }

}
